from openai import OpenAI
from typing import List, Tuple
import os
import time
import threading
import concurrent.futures

# 共享列表和锁
output_list = []
lock = threading.Lock()



file_path = "vlquestions.txt"
# 初始化 OpenAI 客户端
client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"  # 根据本地模型服务配置调整
)

def ask_questions_without_context(file_path: str,model: str = "Qwen2.5-VL-7B-Instruct") -> List[Tuple[str, str]]:
    """
    从文件中读取问题，构造包含图像 URL 和文本提示的请求，调用模型返回回答。

    :param file_path: 文本文件路径（格式：system|user）
    :param image_url: 图像的 URL 地址
    :param model: 模型名称
    :return: 包含 (问题, 回答) 的列表
    """
    results = []
    idx = 0
    context_str = ""  # 用于保存上下文的字符串

    if not os.path.exists(file_path):
        print(f"错误：文件 {file_path} 不存在")
        return results

    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line_number, line in enumerate(file, start=1):
                line = line.strip()
                if not line:
                    continue

                try:
                    system, user,image_url = line.split('|', 2)
                except ValueError:
                    print(f"跳过第 {line_number} 行：格式不正确（缺少 '|' 分隔符）")
                    continue

                # 构造消息结构，包含图像和文本
                messages = [
                    {"role": "system", "content": system.strip()},
                    {
                        "role": "user",
                        "content": [
                            {"type": "image_url", "image_url": {"url": image_url}},
                            {"type": "text", "text": user.strip()}
                        ]
                    }
                ]

                try:
                    start_time = time.time()
                    response = client.chat.completions.create(
                        model=model,
                        messages=messages
                    )
                    answer = response.choices[0].message.content.strip()
                    results.append((user.strip(), answer))
                    end_time = time.time()
                    elapsed = end_time - start_time
                    idx = idx+1
                    print(f"[问题 {idx} ]  响应长度: {len(answer)}, 耗时: {elapsed:.2f}秒")
                    result_string = f"[问题 {idx}] 响应长度: {len(answer)}, 耗时: {elapsed:.2f}秒"
                    with lock:  # 使用锁确保线程安全
                      output_list.append("###########################################################################################################################")
                      output_list.append(image_url)
                      output_list.append(result_string)
                      output_list.append(answer)
                    # 更新上下文字符串
                    context_str += f"User: {user.strip()}\nAssistant: {answer}\n"
                    results.append((user.strip(), answer))
                except Exception as e:
                    print(f"处理第 {line_number} 行时出错：{e}")
                    results.append((user.strip(), f"错误: {str(e)}"))

    except Exception as e:
        print(f"读取文件时出错：{e}")

    return results



# 并发测试函数
def run_concurrent_test(concurrency):
    """
    执行并发测试
    :param concurrency: 并发数量
    :return: 测试结果列表
    """
    results1 = []  # 用于存储每个请求的结果
    # 使用 ThreadPoolExecutor 管理线程池
    with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as executor:
        # 提交并发任务
        futures = [executor.submit(ask_questions_without_context,file_path) for i in range(concurrency)]

        # 遍历已完成的 Future 对象，获取结果
    """            # 遍历已完成的 Future 对象，获取结果
        for future in concurrent.futures.as_completed(futures):
            try:
                result1 = future.result()  # 获取 Future 的结果
                if result1:
                    results1.append(result)  # 将结果添加到列表中
            except Exception as e:
                print(f"An error occurred: {e}")
   """

if __name__ == "__main__":
    CONCURRENCY = 2  # 设置并发数量
    print(f"Starting concurrent test with {CONCURRENCY} threads...")

    # 执行并发测试
    file_path = "vlquestions.txt"
    start_time = time.time()
    test_results = run_concurrent_test(CONCURRENCY)
    end_time = time.time()
    elapsed = end_time - start_time
# 调用函数
    for item in output_list:
        print(item)

    print(f"并发线程  {CONCURRENCY} ， 总运行运行时间  {elapsed}, 平均时间 {elapsed/CONCURRENCY}   ")    
